//
//  ZYEmoticonKeyboardView.swift
//  WBBeta1
//
//  Created by wustzhy on 16/8/18.
//  Copyright © 2016年 Yestin. All rights reserved.
//

import UIKit

class ZYEmoticonKeyboardView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        addSubview(emoticonBottomView)
        addSubview(emoticonPageView)
        
        emoticonBottomView.snp_makeConstraints { (make) -> Void in
            make.leading.bottom.trailing.equalTo(self)
            make.height.equalTo(37)
        }
        emoticonPageView.snp_makeConstraints { (make) -> Void in
            make.top.leading.trailing.equalTo(self)
            make.bottom.equalTo(emoticonBottomView.snp_top)
        }
        
        emoticonBottomView.closureSelEmoticonBtn = { (type) in
//            switch type{
//            case .Default: printLog("default...")
//            case .Emoji: printLog("emoji...")
//            case .Lxh: printLog("lxh.....")
//            }
            let indexPath = NSIndexPath(forRow: 0, inSection: type.rawValue)
            self.emoticonPageView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
    }
    
    private lazy var emoticonBottomView:ZYEmoticonBottomView  = ZYEmoticonBottomView(frame: CGRectZero)
    
    private lazy var emoticonPageView: ZYEmoticonPageView = {
        let view = ZYEmoticonPageView()
        view.pagingEnabled = true
        view.bounces = false
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        
        view.delegate = self//设置代理
        return view
    }()
}

//判断pageView的cell哪个显示的多
extension ZYEmoticonKeyboardView:UICollectionViewDelegate {
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let centerX = SCREENW * 0.5 + scrollView.contentOffset.x
        //获取屏幕显示的cell们，无序的----排序方法.sort方法
        let cells = self.emoticonPageView.visibleCells().sort { (cell1, cell2) -> Bool in
            return cell1.frame.origin.x < cell2.frame.origin.x  //升序
        }
        if cells.count == 2 {
            let firstCell = cells.first!
            let lastCell = cells.last!

            let indexPath: NSIndexPath
            if firstCell.frame.contains(CGPoint(x: centerX, y: 0)) {
                indexPath = emoticonPageView.indexPathForCell(firstCell)!
            }else{
                indexPath = emoticonPageView.indexPathForCell(lastCell)!
            }
            emoticonBottomView.setupCurrentBtnFromKB(indexPath.section)
        }
        
    }
    
    
}

